'use client';

import type { TMetadata } from '@/types';
import { useQuery } from '@tanstack/react-query';
import ErrorPage from '@/app/[locale]/error/error';
import { queryPostNewInfo } from '@/services/api';
import type { IPostNewInfo } from '@/interfaces';
import EditPostCore from '@/app/[locale]/posts/[id]/edit/core';
import { NavbarPage } from '@/app/[locale]/navbar';
import FooterPage from '@/app/[locale]/footer';
import LoadPage from '@/app/[locale]/load/load';

export default function NewPostPage({ metadata }: { metadata: TMetadata }) {
  return (
    <>
      <NavbarPage metadata={metadata} stickyTop={false} />
      <NewPost metadata={metadata} />
      <FooterPage metadata={metadata} />
    </>
  );
}

const NewPost = ({ metadata }: { metadata: TMetadata }) => {
  const queryPostNewInfoQuery = useQuery(
    metadata.all['newPost'].k,
    async () => {
      return (await queryPostNewInfo()) as IPostNewInfo;
    },
    {
      initialData: metadata.all['newPost'].v as IPostNewInfo,
    },
  );

  if (queryPostNewInfoQuery.data) {
    const data = queryPostNewInfoQuery.data;
    return (
      <EditPostCore type="newPost" data={data as any} metadata={metadata} />
    );
  }

  if (queryPostNewInfoQuery.error) {
    return <ErrorPage error={queryPostNewInfoQuery.error} />;
  }

  return <LoadPage />;
};
